<template>
    <view class="pay">
        <view class="tabs">
            <view :class="['tab', { tab_active: payInfo.orderType === index }]" @tap="payInfo.orderType = index"
                v-for="(item, index) in tabs" :key="index">
                {{ item }}
            </view>
        </view>
        <!-- 自提 -->
        <view class="tab_content tab-self" v-show="payInfo.orderType === 0">
            <view class="flex-between">
                <view class="left">
                    <text class="title">{{ merchantInfo.name }}</text>
                    <text class="self_detail sle">{{ merchantInfo.address }}</text>
                </view>
                <view class="right">距离您{{ disDuration?.distance }}</view>
            </view>
            <view class="flex-between time_order">
                <text>预约时间</text>
                <button @tap="visible = true" class="flex-start"><text class="red">立即取餐</text>
                    <image class="right_icon" src="/static/jiantou-right.png" />
                </button>
            </view>
        </view>
        <!-- 外卖 -->
        <view class="tab_content tab-delivery" v-show="payInfo.orderType === 1">
            <view class="flex-between" @tap="getAddress">
                <view class="left">
                    <view v-if="defaultAddress">
                        <text class="title">{{ defaultAddress.address + defaultAddress.detail }}</text>
                        <text> {{ `${defaultAddress.name}(${defaultAddress.gender ? "女士" : "先生"})
                                                    ${defaultAddress.phone}` }}</text>
                    </view>
                    <view v-else class="no_address">请选择收货地址</view>
                </view>
                <image class="right_icon" src="/static/jiantou-right.png" />
            </view>
            <view class="flex-between time_order">
                <text>送达时间</text>
                <button @tap="visible = true" class="flex-start"><text class="red">{{
                    moment().add(disDuration?.duration,
                        'm').format("HH:mm")
                }}</text>
                    <image class="right_icon" src="/static/jiantou-right.png" />
                </button>
            </view>
        </view>
        <view class="order_list m_card">
            <view class="list">
                <view class="list_item flex-start" v-for="item in store.cartItems" :key="item.goodsId">
                    <image :src="item.image" mode="widthFix" />
                    <view class="right">
                        <view class="header flex-between"><text>{{ item.name }}</text><text>￥{{ item.totalPrice
                        }}</text>
                        </view>
                        <view class="rt">{{ item.specs?.join(",") }}</view>
                        <view class="rt">X{{ item.quantity }}</view>
                    </view>
                </view>
            </view>
            <view class="total flex-end">
                <text>合计 </text><text>￥{{ store.cartTotalPrice }}</text>
            </view>
        </view>
        <view class="payment m_card">
            <text class="title">支付方式</text>
            <radio-group @change="changePayment">
                <label class="flex-between">
                    <view class="flex-start"><text>会员余额</text><text>(可用$ {{ 10000 }},剩余 ￥ {{ 10000 -
                        store.cartTotalPrice }})</text></view>
                    <view>
                        <radio :value="0" :checked="true" />
                    </view>
                </label>
                <label class="flex-between">
                    <text>微信支付</text>
                    <radio :value="1" />
                </label>

            </radio-group>

        </view>
        <view class="full_info m_card">
            <view class="full_item flex-between">
                <text class="title">预留电话</text>
                <view class="flex-start"><input style="width:190rpx;" type="text" v-model="payInfo.phone" />
                    <image src="/static/edit.png" />
                </view>
            </view>
            <view class="full_item flex-between">
                <text class="title">订单备注</text>
                <text class="content" @tap="showRemark">{{ payInfo.remark || '口味偏好等要求' }} </text>
            </view>
        </view>
        <button class="add-button" @tap="pay">支付</button>
        <Popup v-model="visible" title="选择送达时间">
            <view class="pop_up flex-start">
                <scroll-view :show-scrollbar="false" scroll-with-animation :scroll-y="true">
                    <view @tap="changeDays(index)" :class="['item', { 'checked': activeDayIndex === index }]"
                        v-for="(item, index) in days" :key="index">{{ item }}</view>
                </scroll-view>
                <scroll-view :show-scrollbar="false" scroll-with-animation :scroll-y="true">
                    <view @tap="changeTimes(index)"
                        :class="['item', 'flex-between', { 'checked': activeTimeIndex === index }]"
                        v-for="(item, index) in times" :key="index"><text>{{ item }}</text>
                        <image v-if="activeTimeIndex === index" src="/static/checked.png" />
                    </view>
                </scroll-view>
            </view>
        </Popup>
        <Popup v-model="remarkVisible" title="备注">
            <view class="remrk_popup">

                <textarea v-model="remark" placeholder="请输入口味偏好等要求" focus :maxlength="30" class="remark_textarea" />
                <button class="confirm_btn" @tap="confirmRemark">确认</button>
            </view>
        </Popup>
    </view>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import request from "@/api/request";
import type { Distance } from "@/types";
import { onLoad, onShow } from "@dcloudio/uni-app";
import Popup from "@/component/popup.vue";
import moment from "moment";
import { useStore } from "@/store";
const store = useStore();
const tabs = ["自取", "外卖"];
const disDuration = ref<Distance>();
const defaultAddress = ref();
const merchantInfo = uni.getStorageSync("merchant_info");
const userInfo = uni.getStorageSync("userInfo");
const visible = ref(false);
const remarkVisible = ref(false);
const activeDayIndex = ref(0);
const activeTimeIndex = ref(0);
const days = ref<string[]>([]);
const times = ref();
const weeks = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
const payInfo = reactive({ payMethod: 0, phone: userInfo.phone, remark: "", orderType: 0, openid: userInfo.openid });
const remark = ref("");
onLoad((payload) => {

    payInfo.orderType = Number(payload!.type);
    const day = moment().days();
    const nextDay = day === 6 ? "0" : day + 1;
    days.value = [`今天(${weeks[day]})`, `明天(${weeks[nextDay]})`];

    changeDays(0);
});
onShow(() => {
    getLocation();
    defaultAddress.value = Object.keys(store.selectedAddress).length ? store.selectedAddress : uni.getStorageSync("defaultAddress");
});
const initialTimes = () => {
    const startOfDay = moment().startOf('day');

    const timeArray = [];

    let currentTime = startOfDay;
    while (currentTime.isBefore(moment().endOf('day')) || currentTime.isSame(moment().endOf('day'))) {
        timeArray.push(currentTime.format('HH:mm'));

        // 增加5分钟
        currentTime.add(5, 'minutes');
    }
    return timeArray;
};
const changeDays = (index: number) => {
    activeDayIndex.value = index;
    if (index === 0) {
        times.value = initialTimes().filter(item => item > moment().add(disDuration.value?.duration, 'm').format("HH:mm"));
        times.value.unshift("立即取餐");
    } else {
        times.value = initialTimes();
    }
};
const changeTimes = (index: number) => {
    activeTimeIndex.value = index;
    console.log(moment().add(activeDayIndex.value, 'days').format("YYYY-MM-DD") + " " + times.value[index]);
    visible.value = false;
};
const pay = async () => {
    if (payInfo.orderType === 1 && !defaultAddress.value) {
        uni.showToast({ title: "请先选择收货地址" });
    } else if (payInfo.orderType === 0 && !payInfo.phone) {
        console.log(payInfo);

        uni.showToast({ title: "预留电话不能为空" });
    } else {
        uni.showLoading({ title: "支付中...", maske: true });
        const params = { ...payInfo, addressId: defaultAddress.value._id, goods: store.cartItems };
        console.log(params);
        // 微信支付
        // const { data } = await request<{}>("/wxPay", params, "POST");
        
        // uni.requestPayment({
        //     provider: "wxpay", orderInfo: "1", ...data,
        //     success: async res => {
        //         store.selectedAddress = {};
        //         store.cartItems = [];
        //         uni.hideLoading();
        //         uni.switchTab({ url: `/pages/orders/index` });
        //         console.log(res)
        //     }, fail: err => {
        //         console.log(err)
        //     }
        // })

        await request<{}>("/createOrder", params, "POST");
        store.selectedAddress = {};
        store.cartItems = [];
        uni.hideLoading();
        uni.switchTab({ url: `/pages/orders/index` });
    }
};
const changePayment = (e: { target: { value: number; }; }) => {
    payInfo.payMethod = e.target.value;

};
const confirmRemark = () => {
    payInfo.remark = remark.value;
    remark.value = "";
    remarkVisible.value = false;
};
const showRemark = () => {
    remark.value = payInfo.remark;
    remarkVisible.value = true;
};

function getLocation() {
    uni.getLocation({
        success: async (res) => {
            const data = await requestDisDuration([res.latitude, res.longitude]);
            disDuration.value = data;
        },
        fail: (err) => {
            uni.showModal({
                title: "地理位置未授权",
                content: "开启定位才可下单",
                success: (res) => {
                    console.log(res);
                    if (res.confirm) {
                        // 调起小程序设置界面
                        goSetting();
                    } else {
                        console.log("用户拒绝定位");
                    }
                },
            });
            console.log(err);
        },
    });
}
async function requestDisDuration(from: number[]) {
    const { data } = await request<Distance>("/getDuration", {
        _id: "662956e5f7fad9e098e0800b",
        from,
    });
    return data;
}
const goSetting = () => {
    uni.openSetting({
        success: (result) => {
            if (result.authSetting["scope.userLocation"]) {
                getLocation();
            }
            console.log(result);
        },
        fail: (err) => {
            console.log(err);

            uni.showToast({ title: "异常失败" });
        }
    });
};

const getAddress = () => {
    uni.navigateTo({ url: "/pages/selectAddress/index" });
};
</script>
<style lang="scss">
page {
    background-color: #f6f6f6 !important;
    padding-bottom: 160rpx;
}

.popup {
    width: 100%;
    height: 600rpx;

}

.pay {
    padding: 20rpx;

    .tabs {
        display: flex;

        .tab {
            width: 50%;
            padding: 20rpx 0;
            text-align: center;
            transition: all 0.2s;
            background: #eee;
        }

        .tab_active {
            background: #fff;
            font-weight: bold;
        }
    }

    .tab_content {
        background: #fff;
        border-radius: 12rpx;
        padding: 30rpx;

        .title {
            font-weight: bold;
            margin-bottom: 20rpx;

        }

        .right_icon {
            width: 20rpx;
            height: 20rpx;
        }

        .time_order {
            padding-top: 30rpx;
            border-top: 1px solid #eee;
            font-size: 28rpx;
            margin-top: 20px;

            button {
                font-size: 28rpx;
                background: none;
                margin: 0;
                padding: 0;

                .red {
                    color: #8b1c1c;
                    margin-right: 10rpx;
                }
            }
        }
    }

    .tab-self {
        .left {

            max-width: calc(100% - 200rpx);
        }

        .self_detail {
            font-size: 24rpx;
            color: #666;
            width: 100%;
        }

        .right {
            font-size: 28rpx;
        }
    }

    .tab-delivery {
        .no_address {
            font-weight: bold;
        }
    }

    .order_list {

        .list {
            border-bottom: 1rpx solid #eee;

            .list_item {
                padding: 20rpx 0;

                image {
                    width: 80rpx;
                    margin-right: 20rpx;
                }

                .right {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;
                    gap: 20px;
                    flex-shrink: 0;

                    .header {
                        font-weight: bold;
                    }

                    .rt {
                        font-size: 24rpx;
                        color: #666;
                    }
                }
            }
        }

        .total {
            padding: 20rpx 0;
        }

    }

    .payment {

        padding: 30rpx;

        .title {
            font-weight: bold;
            margin-bottom: 10rpx;
        }

        label {
            font-size: 28rpx;

            radio {
                transform: scale(0.8);
            }

        }
    }

    .full_info {
        padding: 30rpx;
        font-size: 28rpx;

        image {
            width: 30rpx;
            height: 30rpx;
        }

        .full_item {
            margin: 10rpx 0;
        }
    }
}

.pop_up {
    align-items: flex-start;

    scroll-view {
        max-height: 800rpx;
    }

    .item {
        background: #ffffff;
        padding: 30rpx;
        border-bottom: 1px solid #eee;

        &:last-child {
            border-bottom: none;
        }
    }

    .item.checked {
        color: #214bd5;

        image {
            width: 30rpx;
            height: 30rpx;
        }
    }
}

.remrk_popup {
    padding: 40rpx;

    .remark_textarea {
        background: #eee;
        height: 200rpx;
        width: 100%;
        padding: 40rpx;
        box-sizing: border-box;
        border-radius: 16rpx;
        margin-bottom: 80rpx;
    }

    .confirm_btn {
        background: #214bd5;
        color: #fff;
        padding: 20rpx 0;
        border-radius: 16rpx;
    }
}
</style>